package com.pactera.madp.cp.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.common.core.exception.CheckedException;
import com.pactera.madp.cp.api.dto.sensitive.ReqSensitiveWordDto;
import com.pactera.madp.cp.api.dto.sensitive.SensitiveMsgToEmployeeDTO;
import com.pactera.madp.cp.api.dto.sensitive.SensitiveWordAddDTO;
import com.pactera.madp.cp.api.dto.sensitive.SensitiveWordUpdateDTO;
import com.pactera.madp.cp.api.em.businesslog.EventEnum;
import com.pactera.madp.cp.api.em.permission.ReqPerEnum;
import com.pactera.madp.cp.api.entity.BusinessLogEntity;
import com.pactera.madp.cp.api.entity.WorkContactEntity;
import com.pactera.madp.cp.api.entity.WorkEmployeeEntity;
import com.pactera.madp.cp.api.entity.WorkRoomEntity;
import com.pactera.madp.cp.api.entity.sensitive.SensitiveMatchingRuleEntity;
import com.pactera.madp.cp.api.entity.sensitive.SensitiveWordEntity;
import com.pactera.madp.cp.api.entity.sensitive.SensitiveWordGroupEntity;
import com.pactera.madp.cp.api.entity.sensitive.SensitiveWordsMonitorEntity;
import com.pactera.madp.cp.api.page.SubPage;
import com.pactera.madp.cp.api.vo.SensitiveWorldVO;
import com.pactera.madp.cp.common.util.DateUtils;
import com.pactera.madp.cp.common.util.WxApiUtils;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.sensitiveword.SensitiveWordGroupMapper;
import com.pactera.madp.cp.mapper.sensitiveword.SensitiveWordMapper;
import com.pactera.madp.cp.service.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.interceptor.CacheOperationInvoker;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description: 敏感词库管理
 * @author: Huayu
 * @time: 2021/1/27 11:11
 */
@Slf4j
@Service
@Data
public class SensitiveWordServiceImpl extends ServiceImpl<SensitiveWordMapper, SensitiveWordEntity> implements ISensitiveWordService {

    @Autowired
    private IBusinessLogService businessLogService;
    @Autowired
    private IWorkEmployeeDepartmentService employeeDepartmentService;
    private final SensitiveWordGroupMapper sensitiveWordGroupMapper;
    private SensitiveWordMapper sensitiveWordMapper;
    @Autowired
    private ISensitiveWordsMonitorService sensitiveWordsMonitorService;
    @Autowired
    private SensitiveMatchingRuleService sensitiveMatchingRuleService;
    @Autowired
    private ICorpService corpService;
    @Autowired
    private IWorkEmployeeService employeeService;
    @Autowired
    private IContactService contactService;
    @Autowired
    private IWorkRoomService workRoomService;

    /**
     *
     * @description:删除敏感词
     * @author: Huayu
     * @time: 2021/1/27 11:20
     */
    @Override
    public boolean deleteSensitiveWord(Integer id) {
        boolean remove = sensitiveMatchingRuleService.remove(Wrappers.<SensitiveMatchingRuleEntity>lambdaQuery()
                .eq(SensitiveMatchingRuleEntity::getSensitiveId, id));
        if (remove){
            boolean b = removeById(id);
            return  b;
        }
        return false;
    }

    /**
     *
     *
     * @description:根据筛选条件
     * @return:
     * @author: Huayu
     * @time: 2021/1/27 16:45
     */
    @Override
    public Page<List<SensitiveWorldVO>> getSensitiveWordList(ReqSensitiveWordDto sensitiveWordIndex, ReqPerEnum permission, Page page) {
        //企业Id
        Integer corpId= CorpContextHolder.getCorpId();
        LambdaQueryChainWrapper<SensitiveWordEntity> wrapper = lambdaQuery();
        // 判断是否有权限
        setWrapperPermission(wrapper, permission);
        QueryWrapper<SensitiveWordEntity> queryWrapper = new QueryWrapper<SensitiveWordEntity>();
        queryWrapper.select("id", "name", "group_id", "employee_num", "contact_num", "create_time", "status", "message_alert_status");
        queryWrapper.eq("corp_id",corpId);
        queryWrapper.orderByDesc("create_time");
        //敏感词名称
        if(!StrUtil.isBlank(sensitiveWordIndex.getKeyWords())){
            queryWrapper.like("name",sensitiveWordIndex.getKeyWords());
        }
        //敏感词分组id
        if(sensitiveWordIndex.getGroupId() != null &&  String.valueOf(sensitiveWordIndex.getGroupId()).length() != 0 && sensitiveWordIndex.getGroupId() != 0){
            queryWrapper.eq("group_id",sensitiveWordIndex.getGroupId());
        }

        //匹配词
        if (!StrUtil.isBlank(sensitiveWordIndex.getMatching())) {
            List<SensitiveMatchingRuleEntity> matchings = sensitiveMatchingRuleService.lambdaQuery().like(SensitiveMatchingRuleEntity::getMatchingRule, sensitiveWordIndex.getMatching()).list();
            List<Integer> ids = matchings.stream().map(p -> p.getSensitiveId()).collect(Collectors.toList());
            if (!ids.isEmpty()){
                queryWrapper.in("id", ids);
            }else {
                queryWrapper.eq("id",0);
            }
        }

        page = (Page<SensitiveWordEntity>) page(page, queryWrapper);
        List<SensitiveWordEntity> sensitiveWordEntityList = page.getRecords();
        List<SensitiveWorldVO> worldVOS = new LinkedList<>();
        for (SensitiveWordEntity sensitiveWordEntity:
                sensitiveWordEntityList) {
            QueryWrapper<SensitiveWordGroupEntity> wrapper1 = new QueryWrapper<>();
            wrapper1.select("name").eq("id",sensitiveWordEntity.getGroupId());
            SensitiveWordGroupEntity sensitiveWordGroupEntity = sensitiveWordGroupMapper.selectOne(wrapper1);

            List<SensitiveMatchingRuleEntity> list = sensitiveMatchingRuleService.list(Wrappers.<SensitiveMatchingRuleEntity>lambdaQuery().eq(SensitiveMatchingRuleEntity::getSensitiveId, sensitiveWordEntity.getId()));
            List<String> strings = new LinkedList<>();
            for (SensitiveMatchingRuleEntity s:list) {
                strings.add(s.getMatchingRule());
            }

            SensitiveWorldVO worldVO = new SensitiveWorldVO();
            worldVO.setSensitiveWordId(sensitiveWordEntity.getId());
            worldVO.setName(sensitiveWordEntity.getName());
            worldVO.setEmployeeNum(sensitiveWordEntity.getEmployeeNum());
            worldVO.setContactNum(sensitiveWordEntity.getContactNum());
            worldVO.setCreateTime(DateUtils.asString(sensitiveWordEntity.getCreateTime()));
            worldVO.setStatus(sensitiveWordEntity.getStatus());
            worldVO.setGroupId(sensitiveWordEntity.getGroupId());
            worldVO.setMessageAlertStatus(sensitiveWordEntity.getMessageAlertStatus());
            worldVO.setGroupName(sensitiveWordGroupEntity.getName());
            worldVO.setMatchingRule(strings);
            worldVOS.add(worldVO);
        }
        SubPage subPage = new SubPage();
        subPage.setRecords(worldVOS);
        subPage.setCurrent(page.getCurrent());
        subPage.setSize(page.getSize());
        subPage.setTotal(page.getTotal());
        return subPage;
    }

    /**
     * @author: yangpengwei
     * @time: 2021/3/17 11:19 上午
     * @description 权限管理查询条件配置
     */
    private void setWrapperPermission(LambdaQueryChainWrapper<SensitiveWordEntity> wrapper, ReqPerEnum permission) {
        if (permission == ReqPerEnum.ALL) {
            return;
        }

        LambdaQueryChainWrapper<BusinessLogEntity> logWrapper = businessLogService.lambdaQuery();
        if (permission == ReqPerEnum.DEPARTMENT) {
            // 查询员工所属的部门 id 列表
            List<Integer> idList = employeeDepartmentService.getDeptAndChildDeptEmpIdList();
            logWrapper.in(BusinessLogEntity::getOperationId, idList);
        }

        if (permission == ReqPerEnum.EMPLOYEE) {
            int empId = AccountService.getEmpId();
            logWrapper.eq(BusinessLogEntity::getOperationId, empId);
        }

        // 渠道码业务 id 列表 (渠道码 id 列表)
        List<Integer> idList = logWrapper.in(
                BusinessLogEntity::getEvent,
                Arrays.asList(EventEnum.CHANNEL_CODE_CREATE.getCode(), EventEnum.CHANNEL_CODE_UPDATE.getCode())
        ).list().stream().map(BusinessLogEntity::getBusinessId).collect(Collectors.toList());

        if (idList.isEmpty()) {
            wrapper.eq(SensitiveWordEntity::getId, -1);
        } else {
            wrapper.in(SensitiveWordEntity::getId, idList);
        }
    }

    @Override
    public List<SensitiveWordEntity> getSensitiveWordList(Integer intelligentGroupId) {
        return getSensitiveWordsByGroupId(intelligentGroupId);
    }

    @Override
    public List<SensitiveWordEntity> getSensitiveWordsByGroupId(Integer groupId){
        QueryWrapper<SensitiveWordEntity> sensitiveWordEntityQueryWrapper = new QueryWrapper();
        sensitiveWordEntityQueryWrapper.select("id");
        sensitiveWordEntityQueryWrapper.eq("group_id",groupId);
        return this.baseMapper.selectList(sensitiveWordEntityQueryWrapper);
    }

    @Override
    public List<SensitiveWordEntity> getSensitiveWordsByCorpIdStatus(String[] corpIdArr, int i, String s) {
        QueryWrapper<SensitiveWordEntity> sensitiveWordWrapper = new QueryWrapper();
        List<Integer> list = new LinkedList<>();
        for (String str:
        corpIdArr) {
            list.add(Integer.valueOf(str));
        }
        sensitiveWordWrapper.select(s);
        sensitiveWordWrapper.eq("status",i);
        sensitiveWordWrapper.in("corp_id",list);
        return this.list(sensitiveWordWrapper);
    }

    @Override
    public void updateSensitiveWordById(Object k, Integer employeeNum, Integer contactNum) {
        UpdateWrapper<SensitiveWordEntity> sensitiveWordWrapper = new UpdateWrapper();
        SensitiveWordEntity sensitiveWordEntity = new SensitiveWordEntity();
        sensitiveWordEntity.setEmployeeNum(employeeNum);
        sensitiveWordEntity.setContactNum(contactNum);
        sensitiveWordWrapper.eq("id",k.toString());
        int i = this.baseMapper.update(sensitiveWordEntity,sensitiveWordWrapper);
        if(i > 0){
            log.info("会话信息监测敏感词更新成功");
        }else{
            log.info("会话信息监测敏感词更新失败");
        }
    }

    @Override
    public SensitiveWorldVO getSensitiveWord(Integer id) {
        SensitiveWordEntity one = baseMapper.selectOne(Wrappers.<SensitiveWordEntity>lambdaQuery().eq(SensitiveWordEntity::getId, id));
        SensitiveWorldVO worldVO = new SensitiveWorldVO();
        BeanUtils.copyProperties(one,worldVO);
        List<SensitiveMatchingRuleEntity> list = sensitiveMatchingRuleService.list(Wrappers.<SensitiveMatchingRuleEntity>lambdaQuery()
                .eq(SensitiveMatchingRuleEntity::getSensitiveId, id));
        SensitiveWordGroupEntity entity = sensitiveWordGroupMapper.selectOne(Wrappers.<SensitiveWordGroupEntity>lambdaQuery()
                .eq(SensitiveWordGroupEntity::getId, one.getGroupId()));
        List<String> strings = new LinkedList<>();
        for (SensitiveMatchingRuleEntity s:list) {
            strings.add(s.getMatchingRule());
        }
        worldVO.setSensitiveWordId(one.getId());
        worldVO.setMatchingRule(strings);
        worldVO.setCreateTime(DateUtils.asString(one.getCreateTime()));
        worldVO.setGroupName(entity.getName());
        return worldVO;
    }

    @Override
    public boolean updateSensitiveWord(SensitiveWordUpdateDTO dto) {
        if(CorpContextHolder.getCorpId() == null){
            throw new CheckedException("未选择登录企业，不可操作");
        }
        SensitiveWordEntity sensitiveWordEntity = baseMapper.selectOne(new LambdaQueryWrapper<SensitiveWordEntity>()
                .eq(SensitiveWordEntity::getName, dto.getName())
                .ne(SensitiveWordEntity::getId, dto.getId()));
        if (sensitiveWordEntity != null) {
            throw new CheckedException("该敏感词名称已存在");
        }

        UpdateWrapper<SensitiveWordEntity> updateWrapper = new UpdateWrapper<>();
        if (dto.getGroupId() != null) {
            updateWrapper.set("group_id", dto.getGroupId());
        }
        if (dto.getName() != null && dto.getName().trim().equals("")) {
            updateWrapper.set("name", dto.getName());
        }
        if (dto.getMessageAlertStatus() != null) {
            updateWrapper.set("message_alert_status", dto.getMessageAlertStatus());
        }
        if (dto.getStatus() != null) {
            updateWrapper.set("status", dto.getStatus());
        }
        SensitiveWordEntity entity = new SensitiveWordEntity();
        BeanUtils.copyProperties(dto,entity);
        boolean saveBatch = true;
        int update = baseMapper.updateById(entity);
        if (dto.getMatchingRule() != null && !(dto.getMatchingRule().trim().equals(""))) {
            if (update == 1){
                SensitiveWordEntity wordEntity = baseMapper.selectOne(Wrappers.<SensitiveWordEntity>lambdaQuery().eq(SensitiveWordEntity::getName, dto.getName()));
                ArrayList<SensitiveMatchingRuleEntity> entities = new ArrayList<>();
                String[] split = dto.getMatchingRule().split(",");
                for (String s:split) {
                    SensitiveMatchingRuleEntity ruleEntity = new SensitiveMatchingRuleEntity();
                    ruleEntity.setSensitiveId(wordEntity.getId());
                    ruleEntity.setMatchingRule(s);
                    entities.add(ruleEntity);
                }
                boolean remove = sensitiveMatchingRuleService.remove(Wrappers.<SensitiveMatchingRuleEntity>lambdaQuery()
                        .eq(SensitiveMatchingRuleEntity::getSensitiveId, wordEntity.getId()));
                System.out.println(remove);
                saveBatch = sensitiveMatchingRuleService.saveBatch(entities);
            }
        }
        return saveBatch == true ;
    }

    @Override
    public void sendNotifications(Integer corpId) {
        List<Integer> collect = list(Wrappers.<SensitiveWordEntity>lambdaQuery()
                .eq(SensitiveWordEntity::getCorpId, corpId)
                .eq(SensitiveWordEntity::getStatus, 1)
                .eq(SensitiveWordEntity::getMessageAlertStatus, 1)).stream().map(SensitiveWordEntity::getId).collect(Collectors.toList());
        if (!collect.isEmpty()){
            DateTime yesterday = DateUtil.yesterday();
            DateTime beginOfDay = DateUtil.beginOfDay(yesterday);
            DateTime endOfDay = DateUtil.endOfDay(yesterday);
            //获取昨天客户触发敏感词消息列表
            List<SensitiveWordsMonitorEntity> contacts = sensitiveWordsMonitorService.list(Wrappers.<SensitiveWordsMonitorEntity>lambdaQuery()
                    .eq(SensitiveWordsMonitorEntity::getCorp_id, corpId)
                    .eq(SensitiveWordsMonitorEntity::getSource,1)
                    .ge(SensitiveWordsMonitorEntity::getTriggerTime, beginOfDay)
                    .le(SensitiveWordsMonitorEntity::getTriggerTime, endOfDay)
                    .in(SensitiveWordsMonitorEntity::getSensitiveWordId,collect));

            contacts.forEach(l->{
                //当前触发客户发送消息给成员
                if (l.getReceiverType().equals(1)){
                    SensitiveMsgToEmployeeDTO dto = new SensitiveMsgToEmployeeDTO();
                    WorkEmployeeEntity employeeEntity = employeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                            .eq(WorkEmployeeEntity::getCorpId, corpId)
                            .eq(WorkEmployeeEntity::getId, l.getReceiverId()));

                    WorkContactEntity contactEntity = contactService.getOne(Wrappers.<WorkContactEntity>lambdaQuery()
                            .eq(WorkContactEntity::getCorpId, corpId)
                            .eq(WorkContactEntity::getId, l.getTriggerId()));

                    if (employeeEntity != null && contactEntity != null){
                        dto.setUserId(employeeEntity.getWxUserId());
                        dto.setCorpId(corpId);
                        dto.setContactName(contactEntity.getName());
                        HashMap<String, String> map = new HashMap<>();
                        map.put("content","@"+employeeEntity.getName()+"，你的客户【"+contactEntity.getName()+"】在【"+DateUtil.date(l.getTriggerTime()).toString("yyyy-MM-dd HH:mm:ss")+"】与你交流时触发敏感词【"+l.getSensitiveWordName()+"】");
                        dto.setText(map);
                        getMsgToUser(dto);
                    }
                }

                //当前触发客户发送消息到客户群
                if (l.getReceiverType().equals(3)){
                    SensitiveMsgToEmployeeDTO dto = new SensitiveMsgToEmployeeDTO();
                    WorkRoomEntity roomEntity = workRoomService.getOne(Wrappers.<WorkRoomEntity>lambdaQuery()
                            .eq(WorkRoomEntity::getCorpId, corpId)
                            .eq(WorkRoomEntity::getId, l.getReceiverId()));

                    if (roomEntity != null){
                        WorkEmployeeEntity employeeEntity = employeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                                .eq(WorkEmployeeEntity::getCorpId, corpId)
                                .eq(WorkEmployeeEntity::getId, roomEntity.getOwnerId()));

                        WorkContactEntity contactEntity = contactService.getOne(Wrappers.<WorkContactEntity>lambdaQuery()
                                .eq(WorkContactEntity::getCorpId, corpId)
                                .eq(WorkContactEntity::getId, l.getTriggerId()));

                        if (employeeEntity != null && contactEntity != null){
                            dto.setUserId(employeeEntity.getWxUserId());
                            dto.setCorpId(corpId);
                            dto.setContactName(contactEntity.getName());
                            HashMap<String, String> map = new HashMap<>();
                            map.put("content","@"+employeeEntity.getName()+"，你的客户【"+contactEntity.getName()+"】，于【"+DateUtil.date(l.getTriggerTime()).toString("yyyy-MM-dd HH:mm:ss")+"】在你的客户群【"+roomEntity.getName()+"】交流时触发敏感词【"+l.getSensitiveWordName()+"】");
                            dto.setText(map);
                            getMsgToUser(dto);
                        }
                    }

                }
            });



            //获取昨天员工触发敏感词消息列表
            List<SensitiveWordsMonitorEntity> employees = sensitiveWordsMonitorService.list(Wrappers.<SensitiveWordsMonitorEntity>lambdaQuery()
                    .eq(SensitiveWordsMonitorEntity::getCorp_id, corpId)
                    .eq(SensitiveWordsMonitorEntity::getSource,2)
                    .ge(SensitiveWordsMonitorEntity::getTriggerTime, beginOfDay)
                    .le(SensitiveWordsMonitorEntity::getTriggerTime, endOfDay)
                    .in(SensitiveWordsMonitorEntity::getSensitiveWordId,collect));

            employees.forEach(l->{
                //当前触发成员发送消息给客户
                if (l.getReceiverType().equals(2)){
                    SensitiveMsgToEmployeeDTO dto = new SensitiveMsgToEmployeeDTO();
                    WorkEmployeeEntity employeeEntity = employeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                            .eq(WorkEmployeeEntity::getCorpId, corpId)
                            .eq(WorkEmployeeEntity::getId, l.getTriggerId()));

                    WorkContactEntity contactEntity = contactService.getOne(Wrappers.<WorkContactEntity>lambdaQuery()
                            .eq(WorkContactEntity::getCorpId, corpId)
                            .eq(WorkContactEntity::getId, l.getReceiverId()));

                    if (employeeEntity != null && contactEntity != null){
                        dto.setUserId(employeeEntity.getWxUserId());
                        dto.setCorpId(corpId);
                        dto.setContactName(contactEntity.getName());
                        HashMap<String, String> map = new HashMap<>();
                        map.put("content","@"+employeeEntity.getName()+"，你与客户【"+contactEntity.getName()+"】在【"+DateUtil.date(l.getTriggerTime()).toString("yyyy-MM-dd HH:mm:ss")+"】交流时触发敏感词【"+l.getSensitiveWordName()+"】");
                        dto.setText(map);
                        getMsgToUser(dto);
                    }
                }


                //当前触发成员发送消息到客户群
                if (l.getReceiverType().equals(3)){
                    SensitiveMsgToEmployeeDTO dto = new SensitiveMsgToEmployeeDTO();
                    WorkRoomEntity roomEntity = workRoomService.getOne(Wrappers.<WorkRoomEntity>lambdaQuery()
                            .eq(WorkRoomEntity::getCorpId, corpId)
                            .eq(WorkRoomEntity::getId, l.getReceiverId()));

                    if (roomEntity != null){
                        WorkEmployeeEntity employeeEntity = employeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                                .eq(WorkEmployeeEntity::getCorpId, corpId)
                                .eq(WorkEmployeeEntity::getId, roomEntity.getOwnerId()));

                        WorkEmployeeEntity contactEntity = employeeService.getOne(Wrappers.<WorkEmployeeEntity>lambdaQuery()
                                .eq(WorkEmployeeEntity::getCorpId, corpId)
                                .eq(WorkEmployeeEntity::getId, l.getTriggerId()));

                        if (employeeEntity != null && contactEntity != null){
                            dto.setUserId(employeeEntity.getWxUserId());
                            dto.setCorpId(corpId);
                            dto.setContactName(contactEntity.getName());
                            HashMap<String, String> map = new HashMap<>();
                            map.put("content","@"+employeeEntity.getName()+"，成员【"+contactEntity.getName()+"】，于【"+DateUtil.date(l.getTriggerTime()).toString("yyyy-MM-dd HH:mm:ss")+"】在你的客户群【"+roomEntity.getName()+"】与客户交流时触发敏感词【"+l.getSensitiveWordName()+"】");
                            dto.setText(map);
                            getMsgToUser(dto);
                        }
                    }

                }
            });

        }

    }

    private void getMsgToUser(SensitiveMsgToEmployeeDTO dto) {
        //获取发送应用id
        String wxCorpId = corpService.getById(dto.getCorpId()).getWxCorpId();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser",dto.getUserId());
        jsonObject.put("msgtype","text");
        jsonObject.put("agentid", corpService.getWxSendMsgAgentIdByWxCorpId(wxCorpId));
        jsonObject.put("text",dto.getText());
        String s = jsonObject.toString();
        WxApiUtils.sendMsgToEmployeeByString(s,dto.getCorpId(),wxCorpId);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createSensitiveWords(Map<String, Object> mapData) {
        String nameStr = mapData.get("name").toString();
        String groupId = mapData.get("groupId").toString();
        String[] nameArrStr = nameStr.split(",");
        for (String name:
        nameArrStr) {
            boolean i = nameIsUnique(name);
            if (!i){
                return false;
            }
            //创建敏感词
            createSensitiveWord(name,groupId);
        }
        return true;
    }


    @Override
    public Integer updateSensitiveWordById(Integer sensitiveWordId, String clStr, String clStrVal) {
        UpdateWrapper<SensitiveWordEntity> sensitiveWordEntityUpdateWrapper = new UpdateWrapper();
        sensitiveWordEntityUpdateWrapper.set(clStr,clStrVal);
        sensitiveWordEntityUpdateWrapper.eq("id",sensitiveWordId);
        SensitiveWordEntity sensitiveWordEntity = new SensitiveWordEntity();
        if(clStr.equals("group_id")){
            sensitiveWordEntity.setId(sensitiveWordId);
            sensitiveWordEntity.setGroupId(Integer.valueOf(clStrVal));
        }else{
            sensitiveWordEntity.setId(sensitiveWordId);
            sensitiveWordEntity.setStatus(Integer.valueOf(clStrVal));
        }
        sensitiveWordEntity.setUpdateTime(LocalDateTime.now());
        Integer i = this.baseMapper.update(sensitiveWordEntity,sensitiveWordEntityUpdateWrapper);
        return i;
    }


    @Override
    public boolean nameIsUnique(String name) {
        QueryWrapper<SensitiveWordEntity> sensitiveWordWrapper = new QueryWrapper();
        sensitiveWordWrapper.eq("name",name);
        sensitiveWordWrapper.eq("corp_id", CorpContextHolder.getCorpId());
        SensitiveWordEntity sensitiveWordEntity = this.baseMapper.selectOne(sensitiveWordWrapper);
        if(sensitiveWordEntity != null){
            throw new CheckedException("该敏感词已存在");
        }
            return true;
    }


    @Override
    public boolean createSensitiveWord(SensitiveWordAddDTO dto) {
        if(CorpContextHolder.getCorpId() == null){
            throw new CheckedException("未选择登录企业，不可操作");
        }
        if(dto.getGroupId() == null){
            throw new CheckedException("非法参数");
        }
        if(dto.getName() == null || dto.getName().equals("")){
            throw new CheckedException("非法参数");
        }
        SensitiveWordEntity one = baseMapper.selectOne(Wrappers.<SensitiveWordEntity>lambdaQuery().eq(SensitiveWordEntity::getName, dto.getName()));
        if (one != null){
            throw new CheckedException("敏感词名字重复");
        }
        LinkedList<SensitiveMatchingRuleEntity> entities = new LinkedList<>();
        SensitiveWordEntity entity = new SensitiveWordEntity();
        BeanUtils.copyProperties(dto,entity);
        entity.setCorpId(CorpContextHolder.getCorpId());
        int insert = baseMapper.insert(entity);
        if (insert == 1){
            //lww
            SensitiveWordEntity wordEntity = baseMapper.selectOne(Wrappers.<SensitiveWordEntity>lambdaQuery().eq(SensitiveWordEntity::getName, dto.getName()));
            String[] split = dto.getMatchingRule().split(",");
            for (String s:split) {
                SensitiveMatchingRuleEntity ruleEntity = new SensitiveMatchingRuleEntity();
                ruleEntity.setSensitiveId(wordEntity.getId());
                ruleEntity.setMatchingRule(s);
                entities.add(ruleEntity);
            }
        }
        return sensitiveMatchingRuleService.saveBatch(entities);
    }

    public boolean createSensitiveWord(String name,String groupId){
        //创建敏感词
        SensitiveWordEntity sensitiveWordEntity = new SensitiveWordEntity();
        sensitiveWordEntity.setName(name);
        sensitiveWordEntity.setGroupId(Integer.valueOf(groupId));
        sensitiveWordEntity.setCorpId(CorpContextHolder.getCorpId());
        sensitiveWordEntity.setStatus(1);
        sensitiveWordEntity.setCreateTime(LocalDateTime.now());
        Integer i1 = this.baseMapper.insert(sensitiveWordEntity);
        if(i1 < 1){
            throw new CheckedException("敏感词创建失败");
        }
        //记录业务日志
        QueryWrapper<SensitiveWordEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("name",name);
        queryWrapper.eq("corp_id", CorpContextHolder.getCorpId());
        Integer businessId = this.baseMapper.selectOne(queryWrapper).getId();
        String jsonStr = JSON.toJSONString(sensitiveWordEntity);
        boolean result = businessLogService.createBusinessLog(businessId,jsonStr,EventEnum.SENSITIVE_WORD_CREATE);
        if(!result){
            throw new CheckedException("敏感词创建失败");
        }
        return true;
    }
}
